package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.api.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 角色相关
 */
@Controller
public class RoleHandler {

    @Autowired
    private RoleService roleService;

   // @PreAuthorize("hasRole('部长')")
    //AJAX请求 返回值是JSON
    @ResponseBody
    @RequestMapping("/role/get/page/info.json")
    public ResultEntity<PageInfo<Role>> getPageInfo(
            //keyword有时有 有时无 设置默认为空字符串
        @RequestParam(value = "keyword",defaultValue = "") String keyword,
        //pageNum 默认值设为1
        @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
        //pageSize 默认值设为5
        @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize
    ){

        //调用service方法获取分页数据
        //这里SpringMVC有一个大的try catch 有异常会捕获走自定义异常处理类
        //在自定义异常处理类中已经有了处理机制  所以这里也可以不用try catch

            PageInfo<Role> pageInfo = roleService.getPageInfo(keyword, pageNum, pageSize);

            //封装到ResultEntity对象中返回
            return ResultEntity.successWithData(pageInfo);
    }


    /**
     * 角色维护页 新增角色并保存
     * @param role
     * @return
     */
    @ResponseBody
    @RequestMapping("/role/save.json")
    public ResultEntity<String> saveRole(Role role){
        //这里springMVC会自动映射 传入Role对象即可 需要ajax传入参数中名称与Role中一致
        roleService.saveRole(role);
        return ResultEntity.successWithoutData();
    }

    /**
     * 角色维护页 更新角色并保存
     * @param role
     * @return
     */
    @ResponseBody
    @RequestMapping("/role/update.json")
    public ResultEntity<String> updateRole(Role role){
        //这里springMVC会自动映射 传入Role对象即可 需要ajax传入参数中名称与Role中一致
        roleService.updateRole(role);
        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("/role/remove/by/role/id/array.json")
    //使用@RequestBody接收数据
    public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleIdList){
        /**
         * var requestBody = JSON.stringify(window.roleIdArray);
         */
        roleService.removeRole(roleIdList);
        return ResultEntity.successWithoutData();
    }


}
